package com.example.yrdev.ordering_system.handler;

import android.content.Context;

import com.example.yrdev.ordering_system.Database.DingHanDB;
import com.example.yrdev.ordering_system.Model.CardRecord;
import com.example.yrdev.ordering_system.Model.PurchaseReport;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;
import com.example.yrdev.ordering_system.http.HttpClient;
import com.example.yrdev.ordering_system.http.HttpResponseHandler;
import com.example.yrdev.ordering_system.http.NetWorkConstant;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by luke on 10/30/17.
 */

public class ReportMemberActivityHandler {

    private ArrayList<Object> cardRecordArrayList;
    private Context context;
    private int reportType;
    private   ArrayList<HashMap>hashMapArrayList=new ArrayList<>();
    private  ArrayList<Object>uploadArray=new ArrayList<>();

    public interface  ReportMemberListener{
        void uploadDone();

    }

    private ReportMemberListener reportMemberListener;


    public void setReportMemberListener(ArrayList<Object> cardRecordArrayList,ReportMemberListener reportMemberListener) {

         this.cardRecordArrayList=cardRecordArrayList;
        this.reportMemberListener = reportMemberListener;
        uploadReport();

    }

    public ReportMemberActivityHandler(Context context){

        this.context=context;

    }

    private  void  uploadReport(){

    hashMapArrayList.clear();

        for (Object object : cardRecordArrayList){

            CardRecord respRecord=null;
            if (object instanceof PurchaseReport){

                PurchaseReport report=(PurchaseReport)object;
                respRecord=  DingHanDB.getInstance(context).getCorresPondReport(report);

            }else if (object instanceof CardRecord){

                respRecord=(CardRecord)object;

            }

            if (respRecord.getUploadMark()==0){

                HashMap<String,String> hashMap=new HashMap();
                hashMap.put("vipCardID",respRecord.getCardNo());
                hashMap.put("money",String.valueOf(respRecord.getPurchaseAmount()*100));
                hashMap.put("restMoney",String.valueOf(respRecord.getRemain()*100));
                hashMap.put("rate",respRecord.getDiscountRate().replace("%",""));
                hashMap.put("currentID",String.valueOf(respRecord.getUsageCount()));
                hashMap.put("dateTime",respRecord.getHttpDateTime());
                hashMap.put("employeeID",respRecord.getOperator());
                hashMap.put("devlogNum",(respRecord.getId())+"");
                hashMap.put("logKind",String.valueOf(respRecord.getReportType()));

                hashMapArrayList.add(hashMap);


                uploadArray.add(object);

            }

        }
        uploadIndex=0;
        startUploadProcess();

    }

   private int uploadIndex=0;
   private int uploadMaxCount=5;

    private void startUploadProcess(){

        if (hashMapArrayList.size()>0){


            ArrayList<HashMap>temp=new ArrayList<>();


            while (uploadIndex!=uploadMaxCount){


                if (uploadIndex<hashMapArrayList.size()){


                    GlobalFunction.printTextByTag("uploadIndex:"+uploadIndex+":"+uploadMaxCount);

                    temp.add(hashMapArrayList.get(uploadIndex));

                }


                uploadIndex++;



            }

            GlobalFunction.ToastAlert(context,"正在上传");
            HashMap<String,Object>body=new HashMap<>();
            body.put("num",temp.size());
            body.put("item",temp);

        GlobalFunction.printTextByTag("param:"+body);

            HttpClient.postWithFunction(NetWorkConstant.HTTP_uploadMemberCardPurchaseRecord,body,new HttpResponseHandler(){
                @Override
                protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                    super.handleSuccessMessage(statusCode, headers, responseBody);

                    GlobalFunction.printTextByTag(responseBody);






                    JSONObject jsonObject;
                    try {
                        jsonObject = new JSONObject(responseBody);
                        String resp=jsonObject.getString("response");

                        JSONObject respResponse=new JSONObject(resp);
                        String head=respResponse.getString("head");

                        JSONObject respHead=new JSONObject(head);
                        String respCode=respHead.getString("respCode");
                        GlobalFunction.printTextByTag(responseBody);

                        if (respCode.equals("0000")){





                            if (uploadIndex<hashMapArrayList.size()){  //还没把所有数据上传完

                                uploadMaxCount=uploadMaxCount+5;
                                startUploadProcess();
                            }


                            else
                            {
                                uploadIndex=0;
                                GlobalFunction.ToastAlert(context,"上传成功");

                                changeUploadMark();

                                if (reportMemberListener!=null)
                                    reportMemberListener.uploadDone();


                               // customAdapter.refresh(cardRecordArrayList);
                            }


                            //initializeListData();

                        }else {



                            GlobalFunction.ToastAlert(context,respHead.getString("respMsg"));
                        }

                    }catch (Exception e){
                        GlobalFunction.ToastAlert(context,e.getMessage());

                    }


                }

                @Override
                protected void handleFailureMessage(Request request, IOException e) {
                    super.handleFailureMessage(request, e);
                    GlobalFunction.ToastAlert(context,e.getMessage());



                }
            });

        }else {

            if (reportMemberListener!=null)
                reportMemberListener.uploadDone();

            GlobalFunction.ToastAlert(context,"已把所有记录上传");

        }


    }


    private void changeUploadMark(){
        for (Object object : uploadArray){

            CardRecord respRecord=null;
            if (object instanceof PurchaseReport){

                PurchaseReport report=(PurchaseReport)object;
                respRecord=  DingHanDB.getInstance(context).getCorresPondReport(report);
                respRecord.setUploadMark(1);


            }else if (object instanceof CardRecord){

                respRecord=(CardRecord)object;
                respRecord.setUploadMark(1);
            }


            CardRecord.changeCardReportUploadMark(context,respRecord);






        }
    }




}
